package com.es.www.kyl.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.es.www.kyl.bean.req.client.DoExerciseBaseReq;
import com.es.www.kyl.bean.res.client.QuestionDetailVO;
import com.es.www.kyl.bean.res.client.QuestionInfoVO;
import com.es.www.kyl.constant.BaseConstants;
import com.es.www.kyl.domain.Question;
import com.es.www.kyl.domain.UserPracticeState;
import com.es.www.kyl.util.UserContextHolder;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Estranger
 * @date 2025/8/25
 * description
 */
@Component
public class CommonRoundManager extends AbstractRoundManager {
	@Override
	List<Integer> getinitialQuestionIdList(Integer categoryId, String commonRoundId, String roundId) {
		String key = getRoundKey(null);
		//查询所有题目
		List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
				.eq(Question::getCategoryId, categoryId)
				.eq(Question::getStatus, 1)
		);
		List<String> questionIdList = questionList.stream().map(q -> String.valueOf(q.getId())).collect(Collectors.toList());
		//将本轮次的题目id list 存储在redis中
		redisUtils.rightPushAllList(key + roundId, questionIdList);
		return questionList.stream().map(Question::getId).collect(Collectors.toList());
	}

	@Override
	public QuestionInfoVO continueRound(DoExerciseBaseReq req, BaseConstants.UserPracticeType practiceType) {
		List<Integer> questionIdList = getContinueQuestionIdList(req.getCommonRoundId());
		if (CollectionUtils.isEmpty(questionIdList)) {
			return null;
		}
		//查询用户做题状态
		UserPracticeState userPracticeState = userPracticeStateMapper.selectOne(new LambdaQueryWrapper<UserPracticeState>()
				.eq(UserPracticeState::getCategoryId, req.getCategoryId())
				.eq(UserPracticeState::getUserId, UserContextHolder.getUserId())
				.eq(UserPracticeState::getRoundId, req.getCommonRoundId())
		);
		//获取questionIds中和userPracticeState的lastQuestionId匹配的，下个questionId元素
		int index = 0;
		if (Objects.nonNull(userPracticeState.getLastQuestionId())) {
			index = questionIdList.indexOf(userPracticeState.getLastQuestionId()) + 1;
		}
		QuestionDetailVO questionDetail = exerciseHelper.getQuestionDetail(questionIdList.get(index));
		return QuestionInfoVO.builder()
				.questionDetailInfo(questionDetail)
				.questionIds(questionIdList)
				.roundId(req.getCommonRoundId())
				.build();

	}

	private List<Integer> getContinueQuestionIdList(String roundId) {
		List<String> questionIds = redisUtils.getRangeList(getRoundKey(roundId), 0, -1);
		return questionIds.stream().map(Integer::valueOf).collect(Collectors.toList());
	}
}
